<template>
  <cutting-machine-status  class="chart-content"/>
  <div class="app-container">
    <h3 class="card-title"><span>&nbsp;&nbsp;&nbsp;</span>折弯机床实时状态</h3>
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="monitor-panel">
            <div class="title">
              <i class="el-icon-monitor"></i>
              <span>折弯角度</span>
            </div>
            <div class="value" :style="{ color: calculateAngleColor(bendingData.bendingAngle) }">
              {{ bendingData.bendingAngle || '-' }}°
              <el-tag v-if="bendingData.bendingAngle" size="mini" :type="angleStatusType">
                {{ angleStatusText }}
              </el-tag>
            </div>
            <el-progress
                :percentage="calculateAnglePercentage(bendingData.bendingAngle)"
                :color="calculateAngleColor(bendingData.bendingAngle)"
                :show-text="false"
            />
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card shadow="hover">
          <div class="monitor-panel">
            <div class="title">
              <i class="el-icon-refresh"></i>
              <span>折弯周期</span>
            </div>
            <div class="value">{{ bendingData.circleCount || '-' }} 次</div>
            <div class="circular-chart">
              <el-progress type="circle" :width="80" :percentage="bendingData.circleCount % 100 || 0" />
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card shadow="hover">
          <div class="monitor-panel">
            <div class="title">
              <i class="el-icon-warning"></i>
              <span>液压压力</span>
            </div>
            <div class="value" :class="{ 'warning-text': isPressureWarning }">
              {{ bendingData.bendingPressure || '-' }} MPa
            </div>
            <el-progress
                :percentage="calculatePressurePercentage(bendingData.bendingPressure)"
                :color="calculatePressureColor(bendingData.bendingPressure)"
                :show-text="false"
            />
            <div class="status-text" v-if="bendingData.bendingPressure">
              当前状态: {{ pressureStatus }}
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-divider content-position="center">实时数据流</el-divider>

    <div class="realtime-chart">
      <el-empty v-if="loading" description="数据加载中..."/>
      <div v-else style="width: 1350px; height: 400px;">
        <v-chart class="chart" :option="chartOption" autoresize />
      </div>
    </div>
  </div>

  <div class="chart-card">
    <h3>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;温度变化</h3>
    <show class="chart-content" />
  </div>



</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { getBendingData } from '@/api/equipment-service/machine.js'
import { ElMessage } from 'element-plus'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import { GridComponent, TooltipComponent, TitleComponent } from 'echarts/components'
import VChart from 'vue-echarts'


// 初始化ECharts组件
use([CanvasRenderer, LineChart, GridComponent, TooltipComponent, TitleComponent])


import * as echarts from 'echarts/core';
import { LegendComponent } from 'echarts/components';
import Show from "@/views/equipment-service/machine/show.vue";
import CuttingMachineStatus from "@/views/equipment-service/machine/cuttingMachineStatus.vue";


// 注册必须的组件
echarts.use([
  LegendComponent,
  CanvasRenderer
]);

// 核心数据结构
const bendingData = reactive({
  bendingAngle: null as number | null,
  circleCount: null as number | null,
  bendingPressure: null as number | null,
  timestamp: null as Date | null
})

const loading = ref(true)
const timer = ref<NodeJS.Timeout | null>(null)

// 图表配置
const chartOption = reactive({
  title: { text: '折弯机参数趋势', left: 'center' },
  tooltip: { trigger: 'axis' },
  legend: { data: ['折弯角度', '液压压力'], bottom: 10 },
  grid: { top: 50, right: 20, left: 60, bottom: 50 },
  xAxis: { type: 'time' },
  yAxis: [{
    name: '角度(°)',
    type: 'value'
  }, {
    name: '压力(MPa)',
    type: 'value',
    position: 'right'
  }],
  series: [
    {
      name: '折弯角度',
      type: 'line',
      smooth: true,
      yAxisIndex: 0,
      data: [] as [Date, number][]
    },
    {
      name: '液压压力',
      type: 'line',
      smooth: true,
      yAxisIndex: 1,
      lineStyle: { type: 'dashed' },
      data: [] as [Date, number][]
    }
  ]
})

// 状态计算
const isPressureWarning = ref(false)
const angleStatusType = ref('')
const angleStatusText = ref('')
const pressureStatus = ref('正常')

// 获取折弯机数据
const fetchBendingData = async () => {
  try {
    const  data  = await getBendingData()
    const responseData = data // 根据你的实际API响应结构调整
    console.log(data)
    // 更新核心数据
    Object.assign(bendingData, {
      bendingAngle: responseData.bendingAngle,
      circleCount: responseData.circleCount,
      bendingPressure: responseData.bendingPressure,
      timestamp: new Date()
    })

    // 更新图表数据（限制为最近20条）
    const now = new Date()
    chartOption.series[0].data.push([now, responseData.bendingAngle])
    chartOption.series[1].data.push([now, responseData.bendingPressure])

    if (chartOption.series[0].data.length > 20) {
      chartOption.series[0].data.shift()
      chartOption.series[1].data.shift()
    }

    // 计算状态
    isPressureWarning.value = responseData.bendingPressure > 25
    pressureStatus.value = responseData.bendingPressure > 25 ? '过高警告' : '正常'

    angleStatusType.value = responseData.bendingAngle < 30 ? 'warning' : 'success'
    angleStatusText.value = responseData.bendingAngle < 30 ? '偏低' : '正常'

    loading.value = false
  } catch (error) {
    ElMessage.error('获取折弯机数据失败')
    console.error('API error:', error)
  }
}



// 计算百分比和颜色
const calculateAnglePercentage = (val: number | null) => {
  return val ? Math.min(Math.max(val / 45 * 100, 0), 100) : 0
}

const calculateAngleColor = (val: number | null) => {
  if (val === null) return '#909399'
  return val < 30 ? '#e6a23c' : '#67c23a'
}

const calculatePressurePercentage = (val: number | null) => {
  return val ? Math.min(Math.max(val / 40 * 100, 0), 100) : 0
}

const calculatePressureColor = (val: number | null) => {
  if (val === null) return '#909399'
  return val > 25 ? '#f56c6c' : '#409eff'
}

// 初始化定时请求
onMounted(() => {
  fetchBendingData()
  timer.value = setInterval(fetchBendingData, 1000) // 每3秒刷新一次
})

// 清除定时器
onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value)
  }
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.monitor-panel {
  padding: 15px;
}
.title {
  display: flex;
  align-items: center;
  font-size: 16px;
  color: #606266;
  margin-bottom: 15px;
}
.title i {
  margin-right: 10px;
  font-size: 20px;
}
.value {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #409eff;
}
.circular-chart {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}
.status-text {
  margin-top: 10px;
  font-size: 13px;
  color: #909399;
}
.warning-text {
  color: #f56c6c;
  animation: blink 1s infinite;
}
@keyframes blink {
  50% { opacity: 0.6; }
}
.realtime-chart {
  height: 400px;
  margin-top: 20px;
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
}
.chart {
  width: 100%;
  height: 100%;
}
</style>